package com.cnunicom.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.cnunicom.modules.tra.entity.UnitEntity;
import com.cnunicom.modules.tra.service.UnitService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: dingziyuan
 * @Date: 2019/12/3 10:36
 * @Description: *
 */
// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
public class DemoDataListener extends AnalysisEventListener<UnitEntity> {

    private UnitService unitService;

    public DemoDataListener(UnitService unitService) {
        this.unitService = unitService;
    }

    /**
     * 批处理阈值
     */
    private static final int BATCH_COUNT = 2;
    List<UnitEntity> list = new ArrayList<>();

    @Override
    public void invoke(UnitEntity unitEntity, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(unitEntity));
        list.add(unitEntity);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        unitService.batchSave(this.list); //调用 userService 中的 saveData 方法;
    }
 }
